#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash Muscle-5.1.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y  environment-modules csh time patch libatomic perl-Data-Dumper autoconf automake libtool numactl binutils systemd-devel valgrind flex wget

set -e
yum install -y libstdc++-static patch

wget -t 10 -c -P $buildpath https://github.com/rcedgar/muscle/archive/refs/tags/v5.1.tar.gz
tar xf $buildpath/v5.1.tar.gz -C $buildpath && rm -rf $buildpath/v5.1.tar.gz
cp myutils.cpp.patch $buildpath/muscle-5.1/src
cp timing.h.patch $buildpath/muscle-5.1/src
cd $buildpath/muscle-5.1/src
sed -i "s/ g++/ clang++/" Makefile
patch -f -p0 < ./myutils.cpp.patch
patch -f -p0 < ./timing.h.patch
make -j$nproc
mkdir -p $installpath/muscle-5.1/bin
cp -a Linux/muscle $installpath/muscle-5.1/bin

mkdir -p $installpath/muscle-5.1 && cp -r $buildpath/muscle-5.1/* $installpath/muscle-5.1

cat>"$installpath/muscle-5.1/Muscle_modulefiles"<<EOF
#%Module1.0
conflict muscle
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set MUSCLE \$pwd
setenv MUSCLE \$MUSCLE
prepend-path PATH \$MUSCLE/bin
EOF

rm -rf $buildpath/muscle-5.1

